<?php

namespace Library;

use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Logging\Middleware;
use Doctrine\DBAL\DriverManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMSetup;
use Monolog\Handler\StreamHandler;
use Monolog\Level;

class OrmManager
{
    /**
     * @var EntityManager
     */
    protected EntityManager $manager;

    /**
     * @param array $database
     */
    public function __construct(array $database = [])
    {
        $app = App::make();
        $paths = $app->getConfig("orm-entity-paths");
        $isDevMode= $app->getConfig("debug");
        $dbParams = $app->getConfig("database");
        $dbParams = array_merge($dbParams, $database);
        $driverConfig = null;
        if ($dbParams['debug']&&$isDevMode){
            $driverConfig = $this->enableLogger();
        }
        $connection = DriverManager::getConnection($dbParams, $driverConfig);
        $config = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode);
        $this->manager = new EntityManager($connection, $config);
    }

    /**
     * @return ?Configuration
     */
    protected function enableLogger(): ?Configuration
    {
        $logger = Logger::make("doctrine");
        $driverConfig = new Configuration();
        $driverConfig->setMiddlewares([new Middleware($logger)]);
        return $driverConfig;
    }

    /**
     * @return EntityManager
     */
    public function getManager(): EntityManager
    {
        return $this->manager;
    }


    public function __clone(): void
    {
        // TODO: Implement __clone() method.
    }
}